package com.dlc.shop.seckill.platform.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.dlc.shop.bean.enums.EsOperationType;
import com.dlc.shop.bean.enums.OfflineHandleEventType;
import com.dlc.shop.bean.enums.SendType;
import com.dlc.shop.bean.enums.StationEnum;
import com.dlc.shop.bean.event.EsProductUpdateEvent;
import com.dlc.shop.bean.event.SendMessageEvent;
import com.dlc.shop.bean.model.OfflineHandleEvent;
import com.dlc.shop.bean.model.Product;
import com.dlc.shop.bean.param.NotifyTemplateParam;
import com.dlc.shop.bean.param.OfflineHandleEventAuditParam;
import com.dlc.shop.common.enums.StatusEnum;
import com.dlc.shop.common.exception.YamiShopBindException;
import com.dlc.shop.common.response.ServerResponseEntity;
import com.dlc.shop.common.util.PageParam;
import com.dlc.shop.seckill.common.dto.SeckillPageDto;
import com.dlc.shop.seckill.common.model.Seckill;
import com.dlc.shop.seckill.common.service.SeckillService;
import com.dlc.shop.seckill.common.service.SeckillSkuService;
import com.dlc.shop.seckill.platform.dto.SeckillProdDto;
import com.dlc.shop.security.platform.util.SecurityUtils;
import com.dlc.shop.service.OfflineHandleEventService;
import com.dlc.shop.service.ProductService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;

/**
 * @author LGH
 * @date 2019-08-28 09:36:59
 */
@RestController
@AllArgsConstructor
@RequestMapping("/platform/seckill")
@Tag(name = "平台端秒杀接口")
public class SeckillController {

    private final SeckillService seckillService;
    private final ProductService productService;
    private final ApplicationEventPublisher eventPublisher;
    private final SeckillSkuService seckillSkuService;
    private final OfflineHandleEventService offlineHandleEventService;

    @GetMapping("/page")
    @Operation(summary = "分页查找秒杀信息")
    @PreAuthorize("@pms.hasPermission('platform:seckill:page')")
    public ServerResponseEntity<IPage<SeckillPageDto>> getSeckillPage(PageParam<Seckill> page, Seckill seckill) {
        IPage<SeckillPageDto> seckillPage = seckillService.getPlatformSeckillPage(page, seckill);
        return ServerResponseEntity.success(seckillPage);
    }

    @GetMapping("/info/{seckillId}")
    @Operation(summary = "通过id查询秒杀信息")
    @Parameter(name = "seckillId", description = "秒杀id" , required = true)
    @PreAuthorize("@pms.hasPermission('platform:seckill:info')")
    public ServerResponseEntity<SeckillProdDto> getById(@PathVariable("seckillId") Long seckillId) {
        Seckill seckill = seckillService.getById(seckillId);
        SeckillProdDto dto = new SeckillProdDto();
        dto.setSeckill(seckill);
        dto.setSeckillSkus(seckillSkuService.listSeckillSkuBySeckillId(seckillId));
        Product product = productService.getProductAndLang(seckill.getProdId());
        dto.setProd(product);
        return ServerResponseEntity.success(dto);
    }

    @PutMapping("/invalid/{seckillId}")
    @Operation(summary = "通过id使秒杀商品失效")
    @Parameter(name = "seckillId", description = "秒杀id" , required = true)
    @PreAuthorize("@pms.hasPermission('platform:seckill:invalid')")
    public ServerResponseEntity<Void> invalidById(@PathVariable Long seckillId) {
        Seckill seckill = seckillService.getById(seckillId);
        seckillService.invalidById(seckill);
        seckillSkuService.handSeckillPointSku(seckill);
        productService.removeProdCacheByProdId(seckill.getProdId());
        seckillSkuService.removeSeckillSkuCacheBySeckillId(seckill.getSeckillId());
        seckillService.removeSeckillCache(seckill.getSeckillId(), seckill.getProdId());
        return ServerResponseEntity.success();
    }

    @DeleteMapping("/{seckillId}")
    @Operation(summary = "通过id删除秒杀信息")
    @Parameter(name = "seckillId", description = "秒杀id" , required = true)
    @PreAuthorize("@pms.hasPermission('platform:seckill:delete')")
    public ServerResponseEntity<Void> removeById(@PathVariable Long seckillId) {
        Seckill seckill = seckillService.getById(seckillId);
        Integer oldStatus = seckill.getStatus();
        if (Objects.equals(StationEnum.NORMAL.getValue(), seckill.getStatus())) {
            // 秒杀活动未关闭，无法删除
            throw new YamiShopBindException("yami.seckill.cannot.delete");
        }
        seckillService.invalidById(seckill);
        seckill.setIsDelete(1);
        seckill.setStatus(oldStatus);
        seckillService.updateById(seckill);
        productService.removeProdCacheByProdId(seckill.getProdId());
        seckillSkuService.removeSeckillSkuCacheBySeckillId(seckill.getSeckillId());
        return ServerResponseEntity.success();
    }

    @GetMapping("/getOfflineHandleEventBySeckillId/{seckillId}")
    @PreAuthorize("@pms.hasPermission('platform:seckill:info')")
    @Operation(summary = "通过活动id获取下线信息")
    @Parameter(name = "seckillId", description = "秒杀id" , required = true)
    public ServerResponseEntity<OfflineHandleEvent> getOfflineHandleEventByDiscountId(@PathVariable("seckillId") Long seckillId) {
        OfflineHandleEvent offlineHandleEvent = offlineHandleEventService.getProcessingEventByHandleTypeAndHandleId(OfflineHandleEventType.SECKILL.getValue(), seckillId);
        return ServerResponseEntity.success(offlineHandleEvent);
    }

    @PostMapping("/offline")
    @PreAuthorize("@pms.hasPermission('platform:seckill:update')")
    @Operation(summary = "下线活动")
    public ServerResponseEntity<Void> offline(@RequestBody OfflineHandleEvent offlineHandleEvent) {
        Seckill seckill = seckillService.getById(offlineHandleEvent.getHandleId());
        if (seckill == null) {
            // 未找到该秒杀活动信息
            throw new YamiShopBindException("yami.activity.cannot.find");
        }
        if (Objects.equals(seckill.getIsDelete(),1)) {
            //活动已被删除，请刷新页面重试
            throw new YamiShopBindException("yami.active.is.delete");
        }
        if(Objects.equals(seckill.getStatus(), StatusEnum.OFFLINE.value())){
            //当前商品/活动已违规下架或者正在审核中，不能进行下架操作
            throw new YamiShopBindException("yami.platform.prod.offline.check");
        }
        Long sysUserId = SecurityUtils.getSysUser().getUserId();
        seckillService.offline(seckill, offlineHandleEvent.getOfflineReason(), sysUserId);
        //发送活动下架提醒给商家
        NotifyTemplateParam shopParam = new NotifyTemplateParam();
        shopParam.setShopId(seckill.getShopId());
        shopParam.setActivityId(seckill.getSeckillId());
        shopParam.setActivityName(seckill.getSeckillName());
        shopParam.setSendType(SendType.ACTIVITY_OFFLINE.getValue());
        eventPublisher.publishEvent(new SendMessageEvent(shopParam));
        // 移除缓存
        seckillService.removeSeckillCache(seckill.getSeckillId(), seckill.getProdId());
        eventPublisher.publishEvent(new EsProductUpdateEvent(seckill.getProdId(), null, EsOperationType.UPDATE));
        return ServerResponseEntity.success();
    }

    @PostMapping("/auditSeckill")
    @PreAuthorize("@pms.hasPermission('platform:seckill:update')")
    @Operation(summary = "秒杀活动提交审核")
    public ServerResponseEntity<Void> auditSeckill(@RequestBody OfflineHandleEventAuditParam offlineHandleEventAuditParam) {
        Long sysUserId = SecurityUtils.getSysUser().getUserId();
        Seckill seckill = seckillService.getById(offlineHandleEventAuditParam.getHandleId());
        if (seckill == null) {
            // 未找到该秒杀活动信息
            throw new YamiShopBindException("yami.activity.cannot.find");
        }
        seckillService.auditSeckill(offlineHandleEventAuditParam, sysUserId);
        //发送活动审核提醒给商家
        NotifyTemplateParam shopParam = new NotifyTemplateParam();
        shopParam.setShopId(seckill.getShopId());
        shopParam.setActivityId(seckill.getSeckillId());
        shopParam.setActivityName(seckill.getSeckillName());
        shopParam.setSendType(SendType.ACTIVITY_AUDIT.getValue());
        eventPublisher.publishEvent(new SendMessageEvent(shopParam));
        // 移除缓存
        seckillService.removeSeckillCache(seckill.getSeckillId(), seckill.getProdId());
        eventPublisher.publishEvent(new EsProductUpdateEvent(seckill.getProdId(), null, EsOperationType.UPDATE));
        return ServerResponseEntity.success();
    }
}
